package com.kaishun.study.filestrategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Package: com.kaishun.study.filestrategy
 * @ClassName: StrategyUseService
 * @Author: zhoukaishun
 * @CreateTime: 2021/11/2 10:17
 * @Description: 文件解析服务类
 */
@Component
public class StrategyUseService implements ApplicationContextAware {
    /**
     * 声明一个map用于存储  类型，策略
     */
    private Map<FileTypeEnum, IFileStrategy> iFileStrategyMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // spring 获取 策略服务，放入map中
        Map<String, IFileStrategy> tmepMap = applicationContext.getBeansOfType(IFileStrategy.class);
        tmepMap.values().forEach(iFileStrategy -> {
            iFileStrategyMap.put(iFileStrategy.gainFileType(), iFileStrategy);
        });
    }

    /**
     * 使用时直接调用此方法
     * @param typeEnum
     * @param object
     */
    public void resoleFile(FileTypeEnum typeEnum,Object object){
        IFileStrategy iFileStrategy = iFileStrategyMap.get(typeEnum);
        Optional.ofNullable(iFileStrategy).ifPresent(e->{
            e.resolve(object);
        });
    }

}
